package com.yhf.demoplatform.ProxyPattern.dynamicProxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy {
    static class Target{
        public void foo(){
            System.out.println("target foo");
        }
    }
    public static void main(String[] args) {
        Target target = new Target();
        // 目标是父类，代理是目标的子类
        Target proxy = (Target) Enhancer.create(Target.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("前置增强");
                Object result;
                result = method.invoke(target, args); //用方法反射调用目标
                result = methodProxy.invoke(target,args); //内部没有反射，需要目标
                result = methodProxy.invokeSuper(proxy,args); //内部没有反射，需要代理
                return result;
            }
        });
        proxy.foo();
    }
}
